/*
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2021-10-31 02:20:54
 * @FilePath: \TI插件\js\utils.js
 */

function simulateKeyPress(character) {
  jQuery.event.trigger({ type: "keypress", which: character.charCodeAt(0) });
}

// isInclude柯理化
function skuFilterFn(val) {
  return isInclude(val, skuFilter);
}

// 判断元素是否存在，不存在则等待
function isExits(selector) {
  return $(selector).length == 0;
}

// arrFilter是否包含val
function isInclude(val, arrFilter) {
  for (var i = 0; i < arrFilter.length; i++) {
    if (arrFilter[i] == val) {
      return true;
    }
  }
  return false;
}

// 延时器
function wait(timeout) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, timeout);
  });
}

// 设置local
function localStorageSetItem(name, value) {
  if (typeof value === "object") {
    value = JSON.stringify(value);
  }
  window.localStorage.setItem(name, value);
}

// 获取local
function localStorageGetItem(name) {
  const data = window.localStorage.getItem(name);
  try {
    return JSON.parse(data);
  } catch (err) {
    return data;
  }
}

// 删除local
function localStorageDeleteItem(name) {
  window.localStorage.removeItem(name);
}

// 获取字符串大概长度，中英文大小有区别
function strlen(str) {
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    //单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      len += 2;
    } else {
      len += 3;
    }
  }
  return len;
}

// 复制到剪切板
function $copyText(text) {
  var input = document.createElement("input");
  input.setAttribute("readonly", "readonly"); // 防止手机上弹出软键盘
  input.setAttribute("value", text);
  document.body.appendChild(input);
  // input.setSelectionRange(0, 9999);
  input.select();
  var res = document.execCommand("copy");
  document.body.removeChild(input);
  return res;
}

// 拷贝段落
function copyArticle(event) {
  const range = document.createRange();
  range.selectNode(document.getElementById("descBox")); //需要复制的内容的ID
  const selection = window.getSelection();
  if (selection.rangeCount > 0) selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand("copy");
}

// 延时器
function wait(timeout) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, timeout);
  });
}

// 自定义打印
function log(...s) {
  console.warn("- - - - - [↓] [console.log] [↓] - - - - -");
  console.log("zyp:", ...s);
  console.warn("- - - - - [↑] [console.log] [↑] - - - - -");
}

// 设置input值
function inputValue(el, val, timer = 100) {
  return new Promise((resolve, reject) => {
    if (el instanceof jQuery) {
      el = el[0];
    }
    let evt = document.createEvent("HTMLEvents");
    evt.initEvent("input", true, true);
    el.value = val;
    el.dispatchEvent(evt);
    setTimeout(() => {
      resolve();
    }, timer);
  });
}
